// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import FastClick from 'fastclick'
import router from './router'
import store from './store'
import App from './App'
import { AjaxPlugin, AlertPlugin, ToastPlugin, LoadingPlugin } from 'vux'
import { localStorage } from './js'

Vue.use(AlertPlugin)
Vue.use(ToastPlugin)
Vue.use(LoadingPlugin)
Vue.use(AjaxPlugin)

FastClick.attach(document.body)

Vue.prototype.$localStorage = localStorage

const apiPrefix = ''
const loginTimeOutErrorCode = 'login_timeout_error'

Vue.prototype.http = function (opts) {
  let vue = this
  vue.$vux.loading.show({
    text: '加载中...'
  })
  vue.$http({
    method: opts.method,
    url: apiPrefix + opts.url,
    headers: opts.headers || {},
    params: opts.params || {},
    data: opts.data || {}
  }).then(function (response) {
    vue.$vux.loading.hide()
    opts.success(response.data)
  }).catch(function (error) {
    vue.$vux.loading.hide()
    if (!opts.error) {
      let response = error.response
      let errorMessage = '请求失败'
      console.log(response)
      if (response && response.data) {
        if (response.data.code === loginTimeOutErrorCode) {
          window.location.href = '/'
        }
        if (response.data.msg) {
          errorMessage = response.data.msg
        } else {
          errorMessage = response.statusText
        }
      }
      vue.$vux.alert.show({
        title: '提示',
        content: errorMessage
      })
    } else {
      opts.error(error.response.data)
    }
  })
}

Vue.prototype.get = function (opts) {
  opts.method = 'get'
  this.http(opts)
}

Vue.prototype.post = function (opts) {
  opts.method = 'post'
  this.http(opts)
}

Vue.config.productionTip = false

router.beforeEach((to, from, next) => {
  next()
})

/* eslint-disable no-new */
new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app-box')
